﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Routing;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using System.Web;
using VirtualPress.Infrastructure.Entities.Entity;
using VirtualPress.Portal.Biz;

namespace VirtualPress.Portal.WebLogic
{
    public class DomainRoute : Route
    {
        //private Regex domainRegex;
        private Regex pathRegex;

        public string Domain { get; set; }
        public string[] Namespaces { get; set; }

        public DomainRoute(string domain, string url, object defaults)
            : base(url, new RouteValueDictionary(defaults), new MvcRouteHandler())
        {
            Domain = domain;
        }

        public override RouteData GetRouteData(HttpContextBase httpContext)
        {
            // 构造 regex
            //domainRegex = CreateRegex(Domain);
            pathRegex = CreateRegex(Url);

            // 请求信息
            string requestDomain = httpContext.Request.Headers["host"];
            if (!string.IsNullOrEmpty(requestDomain))
            {
                if (requestDomain.IndexOf(":") > 0)
                {
                    requestDomain = requestDomain.Substring(0, requestDomain.IndexOf(":"));
                }
            }
            else
            {
                requestDomain = httpContext.Request.Url.Host;
            }
            string requestPath = httpContext.Request.AppRelativeCurrentExecutionFilePath.Substring(2) + httpContext.Request.PathInfo;


            // 路由数据
            RouteData data = new RouteData(this, RouteHandler);
            // 域名匹配
            if (requestDomain == "localhost" || new Regex("^(www\\.)?" + this.Domain + "$").IsMatch(requestDomain))
            {
                this.Url = "{controller}/{action}/{id}";
                this.Defaults["controller"] = "home";
                this.Defaults["action"] = "index";
                this.Namespaces = new string[] { "VirtualPress.Portal.Web.Controllers" };
            }
            else
            {
                var IdMapping = MeetingBiz.GetMeetingMapping(requestDomain);
                if (IdMapping != null)
                {
                    this.Url = "{action}";
                    this.Defaults["controller"] = "Conference";
                    this.Defaults["action"] = "home";
                    this.Namespaces = new string[] { "VirtualPress.Portal.Web.Areas.Conference.Controllers" };
                    data.Values["id"] = IdMapping.ConferenceId;
                }
                else //不存在映射
                {
                    data.Values["controller"] = "home";
                    data.Values["action"] = "index";
                    data.DataTokens.Add("Namespaces", new string[] { "VirtualPress.Portal.Web.Controllers" });
                    return data;
                }
            }
            Match pathMatch = pathRegex.Match(requestPath);


            if (pathMatch.Success)//if (domainMatch.Success && pathMatch.Success)
            {
                // 添加默认选项
                if (Defaults != null)
                {
                    foreach (KeyValuePair<string, object> item in Defaults)
                    {
                        if (!data.Values.Keys.Contains(item.Key))
                        {
                            data.Values[item.Key] = item.Value;
                        }
                    }
                }

                // 匹配域名路径
                for (int i = 1; i < pathMatch.Groups.Count; i++)
                {
                    Group group = pathMatch.Groups[i];
                    if (group.Success)
                    {
                        string key = pathRegex.GroupNameFromNumber(i);

                        if (!string.IsNullOrEmpty(key) && !char.IsNumber(key, 0))
                        {
                            if (!string.IsNullOrEmpty(group.Value))
                            {
                                data.Values[key] = group.Value;
                            }
                        }
                    }
                }
                if (Namespaces != null && Namespaces.Length > 0)
                {
                    data.DataTokens.Add("Namespaces", this.Namespaces);
                }
            }

            return data;
        }
        public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
        {
            return base.GetVirtualPath(requestContext, RemoveDomainTokens(values));
        }
        private RouteValueDictionary RemoveDomainTokens(RouteValueDictionary values)
        {
            Regex tokenRegex = new Regex(@"({[a-zA-Z0-9_]*})*-?\.?\/?({[a-zA-Z0-9_]*})*-?\.?\/?({[a-zA-Z0-9_]*})*-?\.?\/?({[a-zA-Z0-9_]*})*-?\.?\/?({[a-zA-Z0-9_]*})*-?\.?\/?({[a-zA-Z0-9_]*})*-?\.?\/?({[a-zA-Z0-9_]*})*-?\.?\/?({[a-zA-Z0-9_]*})*-?\.?\/?({[a-zA-Z0-9_]*})*-?\.?\/?({[a-zA-Z0-9_]*})*-?\.?\/?({[a-zA-Z0-9_]*})*-?\.?\/?({[a-zA-Z0-9_]*})*-?\.?\/?");
            Match tokenMatch = tokenRegex.Match(Domain);
            for (int i = 0; i < tokenMatch.Groups.Count; i++)
            {
                Group group = tokenMatch.Groups[i];
                if (group.Success)
                {
                    string key = group.Value.Replace("{", "").Replace("}", "");
                    if (values.ContainsKey(key))
                        values.Remove(key);
                }
            }

            return values;
        }
        private Regex CreateRegex(string source)
        {
            // 替换
            source = source.Replace("/", @"\/?");
            source = source.Replace(".", @"\.");
            source = source.Replace("-", @"\-");
            source = source.Replace("{", @"(?<");
            source = source.Replace("}", @">([a-zA-Z0-9_]*))");

            return new Regex("^" + source + "$", RegexOptions.IgnoreCase);
        }
    }
}
